package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.UserLoginService;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserLoginServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements UserLoginService {
    @Override
    public ResponseResult login(AdUserDto dto) {
        //校验参数
        if(dto.getName() == null || dto.getPassword() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"没有用户名或者密码");
        }
        //查询数据库用户信息
        LambdaQueryWrapper<AdUser> wrapper = new LambdaQueryWrapper();
        wrapper.eq(AdUser::getName,dto.getName());
        List<AdUser> list = list(wrapper);

        if(list != null || list.size() ==1){
            AdUser adUser = list.get(0);
            String psw = DigestUtils.md5DigestAsHex((dto.getPassword()+adUser.getSalt()).getBytes());
            //对比数据库密码
            if (adUser.getPassword().equals(psw)){
                Map<String,Object> map = new HashMap<>();
                adUser.setPassword("");
                adUser.setSalt("");
                map.put("token", AppJwtUtil.getToken(Long.valueOf(adUser.getId())));
                map.put("user",adUser);
                return ResponseResult.okResult(map);
            }else{
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户不存在");
        }
    }
}
